import serial
import serial.tools.list_ports
import threading

class FpgaSerialCommunication:
    def __init__(self):
        self.data = None#需要发送的数据
        self.serial_port = None #端口名称
        self.serial_thread = None
        self.connected = False #开关状态
        self.recieve_data = "" # 接受的数据
        self.datalist: list = []  # 接受信息list
        self.result = 0

    def list_available_ports(self):
        available_ports = [port.device for port in serial.tools.list_ports.comports()]
        if len(available_ports)==0:
            available_ports.append("无")
        ports_txt=",".join(available_ports)
        print(ports_txt)
        return ports_txt

    #端口名，波特率，字节大小，校验位，停止位，
    def connect(self, port_name, baudrate, bytesize, parity, stopbits):
        try:
            self.serial_port = serial.Serial(port_name,
                                             baudrate=baudrate,
                                             bytesize=bytesize,
                                             parity=parity,
                                             stopbits=stopbits,
                                             timeout=0.05)#读超时时间
            self.connected = True
            #创建一个线程来不阻塞的读取数据
            self.serial_thread = threading.Thread(target=self.read_data)
            self.serial_thread.daemon = True
            self.serial_thread.start()
            return True
        except Exception as e:
            print(f"Failed to connect to {port_name}: {str(e)}")
            return False

    #这部分读取了后，可以直接调用plt_fpga里的add_data
    def read_data(self):
        while self.connected:
            if self.serial_port.in_waiting > 0:
                data = self.serial_port.readline()
                #print(f"Received: {data}")
                self.recieve_data = data #str
                self.result = self.bytes_2to_decimal(self.recieve_data)
                print(f"fpga加入{self.result}")


    def write_data(self, data):
        if self.connected:
            self.serial_port.write(data.encode('ASCII'))

    def disconnect(self):
        if self.connected:
            self.connected = False
            if self.serial_thread:
                self.serial_thread.join()
            if self.serial_port:
                self.serial_port.close()
            return True

    def run_once(self):
        self.write_data('r')

    def bytes_2to_decimal(self, byte_string):
        if byte_string:
            # 将字节串转换为两个16进制数字
            decimal_number = int.from_bytes(byte_string, byteorder='little', signed=False)
            return decimal_number





